package jdbc.mysql.gzpowernode;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

//预编译解决SQL注入问题
public class test05 {

    public static void main(String[] args) {
        System.out.println(login(getUserInfo()) ? "登陆成功" : "登录失败");
    }

    //获取用户信息
    public static Map<String, String> getUserInfo() {
        Map<String, String> user = new HashMap<>();
        Scanner s = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = s.nextLine();
        System.out.println("请输入密码:");
        String password = s.nextLine();
        user.put("name", name);
        user.put("password", password);


        return user;
    }

    public static boolean login(Map<String, String> user) {
        boolean flag = false;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接对象
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gzpowernode?&useSSL=false", "root", "123456");
            //3.获取数据库操作对象
            String sql = "select name ,password from t_user where name=? and password =?";
            ps = conn.prepareStatement(sql);
            //4.执行sql语句
            ps.setString(1, user.get("name"));
            ps.setString(2, user.get("password"));
            rs = ps.executeQuery();
            //5.处理查询结果集
            if (rs.next()) {
                flag = true;
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //6.释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("查询结果集对象未关闭");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("数据库操作对象未关闭");
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("连接对象未关闭");
                }
            }
        }
        return flag;
    }

}
